package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.system.mapper.HatchetMerchantMapper;
import com.ruoyi.system.mapper.HatchetPlanItemMapper;
import com.ruoyi.system.mapper.HatchetPlanMapper;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetPlan;
import com.ruoyi.system.domain.HatchetPlanItem;
import com.ruoyi.system.service.IHatchetPlanService;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 还款计划 服务层实现
 * 
 * @author ruoyi
 * @date 2019-03-01
 */
@Service
public class HatchetPlanServiceImpl implements IHatchetPlanService 
{
	@Autowired
	private HatchetPlanMapper hatchetPlanMapper;
	@Autowired
	private HatchetPlanItemMapper itemMapper;
	@Autowired
	private HatchetMerchantMapper merchantMapper;
	/**
     * 查询还款计划信息
     * 
     * @param iD 还款计划ID
     * @return 还款计划信息
     */
    @Override
	public HatchetPlan selectHatchetPlanById(String iD)
	{
	    return hatchetPlanMapper.selectHatchetPlanById(iD);
	}
	
	/**
     * 查询还款计划列表
     * 
     * @param hatchetPlan 还款计划信息
     * @return 还款计划集合
     */
	@Override
	public List<HatchetPlan> selectHatchetPlanList(HatchetPlan hatchetPlan)
	{
	    return hatchetPlanMapper.selectHatchetPlanList(hatchetPlan);
	   
	}
	
    /**
     * 新增还款计划
     * 
     * @param hatchetPlan 还款计划信息
     * @return 结果
     */
	@Override
	public int insertHatchetPlan(HatchetPlan hatchetPlan)
	{
	    return hatchetPlanMapper.insertHatchetPlan(hatchetPlan);
	}
	
	/**
     * 修改还款计划
     * 
     * @param hatchetPlan 还款计划信息
     * @return 结果
     */
	@Override
	public int updateHatchetPlan(HatchetPlan hatchetPlan)
	{
	    return hatchetPlanMapper.updateHatchetPlan(hatchetPlan);
	}

	/**
     * 删除还款计划对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteHatchetPlanByIds(String ids)
	{
		return hatchetPlanMapper.deleteHatchetPlanByIds(Convert.toStrArray(ids));
	}

	/**
	 * 通过大计划的id查询银行名称和用户名
	 * @param id
	 * @return
	 */
	public HatchetPlan selectBankNameById(String id) {
		return hatchetPlanMapper.selectBankNameById(id);
	}

	/**
	 * 代理商查询下属商户的计划列表
	 * @param merchantIdList
	 * @return
	 */
	public List<HatchetPlan> selectHatchetPlanForDLS(HatchetPlan hatchetPlan) {
		return hatchetPlanMapper.selectHatchetPlanForDLS(hatchetPlan);
	}
	
	/**
	 * 查询计划完成进度 
	 * @param planId 大计划id
	 * @return 
	 */
	public double selectPlanProgress(String planId) {
		//1.查询大计划的所有明细
		HatchetPlanItem item1 = new HatchetPlanItem();
		item1.setPlanId(planId);
		List<HatchetPlanItem> itemListAll = itemMapper.selectHatchetPlanItemList(item1);
		//2.查询大计划下执行成功的小计划
		item1.setSTATUS("10B");
		List<HatchetPlanItem> itemListSuccess= itemMapper.selectHatchetPlanItemList(item1);
		int sizeAll = itemListAll.size();
		 int sizeSuccess = itemListSuccess.size();
		if (sizeAll==0 ) {
			return 0d;
		}
		double progress = new BigDecimal((float)sizeSuccess/sizeAll).doubleValue();
		progress = StringUtils.twoDecimals(progress);
		return progress;
	}
	
	/**
	 * 提交计划
	 * @param plan
	 * @return
	 */
	@Transactional
	public Map<String, Object> submitPlan(String plan,String loginName) {
		Map<String, Object> map = new HashMap<>();
		JSONObject json = JSONObject.fromObject(plan);
		JSONArray itemsArray = (JSONArray) json.get("items");
		String customizeCity =""; 
		List<HatchetPlanItem> items = new ArrayList<>();
		String planId = StringUtils.randomUUID();
		if(StringUtils.isEmpty(itemsArray)) {
			throw new RuntimeException("通道异常，请联系客服");
		}
		//创建计划明细
		for (int i=0;i<itemsArray.size();i++) {
			String itemId = StringUtils.randomUUID();
			JSONObject object = itemsArray.getJSONObject(i);
			customizeCity =object.getString("citycode");
			String money = object.getString("money");
			String status = "10A";
			String plan_time = object.getString("time"); // 时间戳
			String increase_id = object.getString("bindid");
			String toid = object.getString("bindid");
			String toMoney = object.getString("money");
			String type = object.getString("type");
			String groupNum = object.getString("groupNum");
			String customizecity = "";
			String cityindustry = "";
			String cityindustryName = "";
			String _customizecity = "";
			if (object.containsKey("customizecity")
					&& org.apache.commons.lang3.StringUtils.isNotBlank(object.getString("customizecity"))) {
				if (object.getString("type").equals("sale")) {
					customizecity = object.getString("customizecity");
					if (org.apache.commons.lang3.StringUtils.isBlank(_customizecity)
							&& org.apache.commons.lang3.StringUtils.isNotBlank(customizecity)) {
						_customizecity = customizecity;
					}
					cityindustry = object.getString("cityindustry");// 这个acqMerchantNo
					if (object.containsKey("cityindustryName")) {
						cityindustryName = object.getString("cityindustryName");// 行业名称
					}
				} else {
					customizecity = null;
					cityindustry = null;
					cityindustryName = null;
				}
			} else {
				customizecity = null;
				cityindustry = null;
				cityindustryName = null;
			}
			HatchetPlanItem item = new HatchetPlanItem();
			item.setID(itemId);
			item.setMerchantId(json.getString("merchantId"));
			item.setFromIncreaseId(increase_id);
			item.setPlanId(planId);
			item.setMONEY(new BigDecimal(money));
			item.setSTATUS(status);
			item.setPlanTime(DateUtils.parseDate(plan_time));
			item.setOrderId("");
			item.setToIncreaseId(toid);
			item.setToMoney(new BigDecimal(toMoney));
			item.setTYPE(type);
			item.setGroupNumber(groupNum);
			item.setCustomizeCity(customizecity);
			item.setCityIndustry(cityindustry);
			item.setIndustryName(cityindustryName);
			int insertHatchetPlanItem = itemMapper.insertHatchetPlanItem(item);
			if(insertHatchetPlanItem<1) {
				throw new RuntimeException("计划明细创建失败");
			}
			items.add(item);
		}
		/*//批量添加计划明细
		int insertByBatch = itemMapper.insertByBatch(items);
		if (insertByBatch<1) {
			
		}*/
		
		//创建大计划
		HatchetPlan hatchetPlan = new HatchetPlan();
		hatchetPlan.setID(planId);
		//用户id
		hatchetPlan.setMerchantId(json.getString("merchantId"));
		hatchetPlan.setSTATUS("10A");
		hatchetPlan.setCreateTime(new Date());
		hatchetPlan.setUpdateTime(new Date());
		//计划金额
		hatchetPlan.setPlanAmt(new BigDecimal(json.getString("8")));
		//周转金
		hatchetPlan.setCbAmt(new BigDecimal(json.getString("total_zhj")));
		String planTime =json.getString("plan_time");
		String[] times = planTime.split("-");
		//开始时间
		hatchetPlan.setStartTime(new Date());
		//结束时间
		hatchetPlan.setEndTime(DateUtils.parseDate(times[1]+" 23:59:59"));
		hatchetPlan.setTYPE("10B");
		//还款手续费
		hatchetPlan.setSaleFree(new BigDecimal(json.getString("rate_money")));
		//笔数费
		hatchetPlan.setPayFree(new BigDecimal(json.getString("times_money")));
		//费率
		hatchetPlan.setRATE(new BigDecimal(json.getString("rate").substring(0, json.getString("rate").length()-1)));
		//单笔笔数费
		hatchetPlan.setPRO(new BigDecimal("1"));
		//手续费的手续费
		hatchetPlan.setThawTrx(new BigDecimal(json.getString("free_free")));
		//每天还款次数
		hatchetPlan.setEveryNum(Integer.parseInt(json.getString("second")));
		//是否落地
		hatchetPlan.setIsGround(1);
		//通道编号
		hatchetPlan.setAcqCode(json.getString("acq_code"));
		//城市
		hatchetPlan.setCustomizeCity(customizeCity);
		//行业
		hatchetPlan.setCityIndustry("1");
		//计划明细
		hatchetPlan.setSourceItem(itemsArray.toString());
		HatchetMerchant merchant = merchantMapper.selectHatchetMerchantByNo(loginName);
		if (StringUtils.isNotNull(merchant)) {
			hatchetPlan.setBrokerId(merchant.getID());
		} else {
			throw new RuntimeException("系统繁忙：当前用户查找失败");
		}
		int insertHatchetPlan = insertHatchetPlan(hatchetPlan);
		if (insertHatchetPlan<1) {
			throw new RuntimeException("计划创建失败");
		}
		/*map.put("total_zhj", total_zhj.toString());// 周转金
		map.put("rate_money", rate_money.toString());//手续费
		map.put("times_money", times_money.toString());//笔数费
		map.put("toalFree", toalFree.toString());//总手续费
		map.put("free_free", free_free.toString());//手续费的费用
		map.put("second", second);//每天的次数
		map.put("plan_time", myplan.get("plan_time") + "");//日期区间
		String string = JSONArray.fromObject(list).toString();
		map.put("items", list);//小计划列表
		map.put("acq_code", acq_code);//通道编号
		return null;*/
		map.put("status", BusinessStatus.SUCCESS);
		map.put("msg", "计划创建成功");
		return map;
	}

	/**
	 * 查询计划总金额
	 * @param hatchetPlan
	 * @return
	 */
	public BigDecimal selectPlanSumMoney(HatchetPlan hatchetPlan) {
		BigDecimal selectPlanSumMoney = hatchetPlanMapper.selectPlanSumMoney(hatchetPlan);
		if (StringUtils.isNull(selectPlanSumMoney)) {
			return new BigDecimal("0");
		}else {
			return selectPlanSumMoney;
		}
		
	}

	/**
	 * 代理商查询计划总金额 
	 * @param hatchetPlan
	 * @return
	 */
	public BigDecimal selectPlanDLSSumMoney(HatchetPlan hatchetPlan) {
		// TODO Auto-generated method stub
		 BigDecimal selectPlanDLSSumMoney = hatchetPlanMapper.selectPlanDLSSumMoney(hatchetPlan);
		if (StringUtils.isNull(selectPlanDLSSumMoney)) {
			return new BigDecimal("0");
		} else {
			return selectPlanDLSSumMoney;
		}
		 
	}
	
}
